package top.swimmer.tokenizer.core;

import top.swimmer.tokenizer.dictionary.DictionaryFactory;
import top.swimmer.tokenizer.entities.Word;

import java.util.*;
import java.util.stream.Collectors;

import static top.swimmer.tools.number.NumberUtils.min;

/**
 * Created by xiaoyou on 16-12-11.
 */
public class ReverseMaximumMatching extends AbstractSegmentation {

    @Override
    public List<Word> segmentation(String text) {
        Deque<Word> results = new ArrayDeque<>();
        int wordMaxLength = min(getDictionary().getMaxWordLength(), text.length());
        int end = text.length();

        while (end > 0) {
            int currentLength = min(wordMaxLength, end);
            boolean isSeg = false;
            while (end - currentLength >= 0) {
                if (getDictionary().contains(text, end - currentLength, currentLength)) {
                    addWord(results, text, end - currentLength, currentLength);
                    isSeg = true;
                    break;
                } else if (--currentLength <= 0) {
                    break;
                }
            }

            if (isSeg) {
                end -= currentLength;
            } else {
                addWord(results, text, --end, 1);
            }
        }

        return new ArrayList<>(results);
    }

    public static void main(String[] args) {
        ReverseMaximumMatching minimumMatching = new ReverseMaximumMatching();
        System.out.println(minimumMatching.segmentation("南"));
        System.out.println(minimumMatching.segmentation("贵是"));
        System.out.println(minimumMatching.segmentation("贵是贵是贵是贵是贵是贵是贵是贵是"));
        System.out.println(minimumMatching.segmentation("南京市长江大桥"));
        System.out.println(minimumMatching.segmentation("贵是哈南京市长江大桥哈贵是"));
        System.out.println(minimumMatching.segmentation("我们都有一个家"));
        System.out.println(minimumMatching.segmentation("阿基受到法律看还是来开发"));
        System.out.println(minimumMatching.segmentation("长春市长王铁路"));
        System.out.println(minimumMatching.segmentation("自如有家是一家创造品质租住产品的互联网公司"));
        System.out.println(minimumMatching.segmentation("无论是后来故事怎么了"));
        System.out.println(minimumMatching.segmentation("也要让后来人生精彩着"));
        System.out.println(minimumMatching.segmentation("无论是后来故事怎么了，也要让后来人生精彩着！"));
        System.out.println(minimumMatching.segmentation("也要！@#让后\"来人%……&生精彩着"));
        System.out.println(minimumMatching.segmentation("他不管三七二十一就骂她是二百五，我就无语了，真是个二货。他还问我：“杨老师，‘二货’是什么意思？”"));
    }
}
